package sip;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.List;

/**
 * Class to Manage Basal Profiles
 * @author Stephen
 */
public class BasalProfileFactory {
    ///Keys are Strings as BasalProfile Names and values are the BasalProfile objects
    public HashMap<String,BasalProfile> mUserBasalProfiles;
    private static String msBasalProfileFileName = "BasalProfiles.txt";
    
    ///End of Line characters are OS dependent
    private static String eol = System.getProperty("line.separator");
    
    /** Constructor*/
    public BasalProfileFactory(){
        mUserBasalProfiles = new HashMap();
        File f = new File(msBasalProfileFileName);
        //todo:  read in the basal profiles when this is created?
        if(f.exists())
        {
            //we should read the file here?
        }
        else
        {
            //load default
        }
    }
    
    
    ///Use to save the basal profiles to a file
    public void saveBasalProfiles() {
        try {
//            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(BasalProfileFileName, true))); //append to file
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(msBasalProfileFileName, false))); //overwrite file
            for (Iterator<Entry<String, BasalProfile>> it = mUserBasalProfiles.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, BasalProfile> entry = it.next();
                String key = entry.getKey();
                BasalProfile value = entry.getValue();
                out.print( key + "," );
                for(int iter = 0; iter < 24; iter++)
                {
                    out.print( value.mProfile[iter] );
                    if(iter != 23)
                    {
                        out.print( "," );
                    }
                }
                out.print( eol );
            }
            
            out.close();
        }   
            catch (IOException e) {
            System.out.println("ERROR:  Exception:  " + e.toString());
        }
    }
    
    ///Reads the basal profiles from a file, should probably be a static function...
    public void readBasalProfiles() {
        try {
            BufferedReader CSVFile = new BufferedReader(new FileReader(msBasalProfileFileName));

            String dataRow = CSVFile.readLine();
            while(dataRow != null){
                String[] dataArray = dataRow.split(",");
                int counter = 0;
                String key = new String();
                BasalProfile bp = new BasalProfile();
                for(String item:dataArray){
                    if( counter == 0 )
                    {
                        key = item;
                    }
                    else
                    {
                        bp.mProfile[counter-1] = Float.parseFloat(item);
                    }
                    counter = counter + 1;
                }
                bp.setProfileName(key);
                mUserBasalProfiles.put(key, bp);
                dataRow = CSVFile.readLine();
            }
            CSVFile.close();
        } catch (IOException e) {
            System.out.println("ERROR:  Exception:  " + e.toString());
        }
    }

    
    ///use to activate a particular profile by giving a specific profile to activate
    public void activateProfile(BasalProfile profile)
    {
        
        activateProfile(profile.getProfileName());
    }
    
    ///use to activate a particular profile by name
    public void activateProfile(String profileName) {
        for(Iterator<Entry<String, BasalProfile>> it = mUserBasalProfiles.entrySet().iterator(); it.hasNext();)
        {
            //first iterate over all profiles in HashMap and set active status to false
            Map.Entry<String, BasalProfile> entry = it.next();
            entry.getValue().setActiveStatus(false);
        }
        //then set the desired profile status to true
        mUserBasalProfiles.get(profileName).setActiveStatus(true);
        SipLogger.Instance().info("Setting " + profileName + " as active profile");
        // start insulin according to the activated profile
        BasalProfile basalProfileToBeActivated = getBasalProfile(profileName);
        // send this to BasalProfileInsulinThread class
        
        
    }
    
    ///Use to get an arraylist of strings containing the names of each of the basal profiles
    public List<String> getBasalProfileNames()
    {
       /* ArrayList profileNames = new ArrayList();
        for(Iterator<Entry<String, BasalProfile>> it = mUserBasalProfiles.entrySet().iterator(); it.hasNext();)
        {
            //first iterate over all profiles in HashMap and set active status to false
            Map.Entry<String, BasalProfile> entry = it.next();
            profileNames.add(entry.getKey());
        }
        return profileNames;*/
    //    String[] profileNames = new String[20];
        List<String> profileNames = new ArrayList();
        int i =0;
        for(Iterator<Entry<String, BasalProfile>> it = mUserBasalProfiles.entrySet().iterator(); it.hasNext();)
        {
            //first iterate over all profiles in HashMap and set active status to false
           Map.Entry<String, BasalProfile> entry = it.next();
           mUserBasalProfiles.entrySet().iterator();
           profileNames.add(entry.getKey());
           // profileNames[i]= (entry.getKey());
            i++;
        }
        return profileNames;
        
    }
    
    ///Use to add a profile to the user basal profile hash map
    public void addProfile(String profileName, BasalProfile profile)
    {
        SipLogger.Instance().info("Adding " + profileName + " to list of profiles");
        mUserBasalProfiles.put(profileName, profile);
    }
    
    ///Use to delete a basal profile from the user basal profile hash map
    public void removeProfile(String profileName)
    {
        SipLogger.Instance().info("Removing " + profileName + " from list of profiles");
        mUserBasalProfiles.remove(profileName);
        saveBasalProfiles();
    }
    
    ///Use to get a particular basal profile based on the profile name
    public BasalProfile getBasalProfile(String profileName)
    {
        return mUserBasalProfiles.get(profileName);
    }

    ///Used for testing this class
    
       public static void main (String args[]) {
           BasalProfileFactory profileFactory = new BasalProfileFactory();
           profileFactory.readBasalProfiles();
       }
       
//     public static void main (String args[]) {
//         BasalProfileFactory profileFactory = new BasalProfileFactory();
//        
//         BasalProfile profile1 = new BasalProfile();
//         for(int iter = 0; iter < 24; iter++)
//         {
//            profile1.mProfile[iter] = iter + 1;
//         }
//         profileFactory.mUserBasalProfiles.put("First", profile1);
//        
//         BasalProfile profile2 = new BasalProfile();
//         for(int iter = 0; iter < 24; iter++)
//         {
//            profile2.mProfile[iter] = profile1.mProfile[iter] + 1;
//         }
//         profileFactory.mUserBasalProfiles.put("Second", profile2);
//        
//         BasalProfile profile3 = new BasalProfile();
//         for(int iter = 0; iter < 24; iter++)
//         {
//            profile3.mProfile[iter] = profile2.mProfile[iter] + 1;
//         }
//         profileFactory.mUserBasalProfiles.put("Third", profile3);
//        
//         profileFactory.saveBasalProfiles();
//         profileFactory.readBasalProfiles();
//         
//         //Display the profiles
//         for (Iterator<Entry<String, BasalProfile>> it = profileFactory.mUserBasalProfiles.entrySet().iterator(); it.hasNext();)
//         {
//             Map.Entry<String, BasalProfile> entry = it.next();
//             String key = entry.getKey();
//             BasalProfile value = entry.getValue();
//             System.out.println(key);
//             value.display();
//         }
//     }    
}
